package com.example.dg;

import cn.hutool.core.io.FileUtil;
import cn.hutool.extra.mail.MailUtil;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.example.dg.entity.Entity;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;

@Controller
@RequestMapping("/pay")
@Slf4j
public class PayController2 {
    //appid
    private final String APP_ID = "2021000122674456";
    //应用私钥
    private final String APP_PRIVATE_KEY = "MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQDgixhkaYiVJQeEFUOJiki6bnRlaDYqtn+1C7Bxlm9XAmJ2GSbUh9UC3ciyt9Ggd3q7GmQC53MK+tnctkt4EHjiZp6tDrW5YieVF5sZG2idK9DKdi55KVHknpZdhqC5ZxQtWVdrWUsVi00Y5dQmK0aM3fs+Eu8zG3XmsfJ93RKJtmg1sx2Jcl6ROEPzMEZkrv1XkYHFkqcad0LTAbb3VX8rXHFQv9BrjS9TUvlonfD9ASzE6e38rvRjf7Mqj2wk0yWbvdNSQAj0J6iQlw+ugcGTyrew0mnVrgCL0I092YI0k53tR6WgXK9s5oESeqkcrL0rZJOmvw9Jfjiai7YE0cM5AgMBAAECggEANQ0oCjFU78f76p0Lg+eEH2gRYBQrGBReP+wvF+cvDyOlF7oBjp05GqBD1tXPVVZlTOeDUZxVdfammpsHYaqipPsR6llbXh1utK8LGfd71AaSIgOiH0Y/7v/5DsfMGYHdJonBOb+zGbf70zIZ2ZrH5Ghd/+CBW1XVmVfZrxsYUiixSxMHoBa0afc84c94fo1HAI7gZsaeWc+i/5JGLa/vxKowT7/iSiK/qUPf9Lz9plE/F+5Q7BJ4Ui7QElK/VSJgvNUtws876Nz56nt/JAbkxgFOMb2VFfQil1EEEd8jm+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Y0duOR0EF+ObWrFJTdIQI2rwBKUbUDP8mJEuXNk4eAZ4mP8BV4Qli5Eo5IcBVoiLFs2Vber3PeNteoKkCUF/hSrn2qAB/VHgueD1Qvmncmh5Z6ny0yMzDwxRWO9VzCFVLSroaNvCKU+Wi20bBY3O3dKxVdScrRau4l87k7lre7N2Wsk+1LgJJn7RP0VtGeOOkojse5ZoYIUr97qGzZqdrIkWBArXTWgNm6WPnvkiZ3Qqrtzd858hdb3ueBMsUPdImFl5hDh1yrSCIGuRbxJKd+z8gGhJZljoLDTHOMZ4BXyqONewIDAQAB";
    //这是沙箱接口路径,正式路径为https://openapi.alipay.com/gateway.do

    //    private final String GATEWAY_URL = "https://openapi.alipay.com/gateway.do";
    private final String GATEWAY_URL = "https://openapi-sandbox.dl.alipaydev.com/gateway.do";
    private final String FORMAT = "JSON";
    //签名方式
    private final String SIGN_TYPE = "RSA2";
    //支付宝异步通知路径,付款完毕后会异步调用本项目的方法,必须为公网地址
//    private final String NOTIFY_URL = "http://htyew7.natappfree.cc/pay/returnUrl";
    private final String NOTIFY_URL = "http://localhost:8081/ssmDemo/notify_url.jsp";
    //支付宝同步通知路径,也就是当付款完毕后跳转本项目的页面,可以不是公网地址
//    private final String RETURN_URL = "http://127.0.0.1";
    private final String RETURN_URL = "http://127.0.0.1:5502/ShoppingCart.html";

    @RequestMapping("alipay")
    public void alipay(Integer id,HttpServletRequest req, HttpServletResponse httpResponse) throws IOException, InterruptedException {

        Entity order = new Entity();

        //实例化客户端,填入所需参数
        AlipayClient alipayClient = new DefaultAlipayClient(GATEWAY_URL, APP_ID, APP_PRIVATE_KEY, FORMAT, CHARSET, ALIPAY_PUBLIC_KEY, SIGN_TYPE);
        AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();
        //在公共参数中设置回跳和通知地址
        request.setReturnUrl(RETURN_URL);

        request.setNotifyUrl(NOTIFY_URL);
        //根据订单编号,查询订单相关信息
//        Order order = IPayService.selectById(orderId);
        //商户订单号，商户网站订单系统中唯一订单号，必填
//        String out_trade_no = orderId.toString(10012301);
        Random random=new Random();
        int out_trade_no=random.nextInt(1000000026);
        //付款金额，必填
//        Random random2=new Random();
        String priceStr = req.getParameter("price");
        int price = Integer.parseInt(priceStr);

//        int total_amount=random2.nextInt(11111);
        //订单名称，必填
        String nameStr =  req.getParameter("name");
        String name = nameStr.toString();
        //商品描述，可空
//        String body = "iPhone 13 Pro Max";
//        String typeStr = req.getParameter("type");
//        String type = typeStr.toString();

        request.setBizContent("{\"out_trade_no\":\"" + out_trade_no + "\","
                + "\"total_amount\":\"" + price + "\","
                + "\"subject\":\"" +  name  + "\","
//                + "\"body\":\"" + type + "\","
                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");
        String form = "text.html";

        try {
            form = alipayClient.pageExecute(request).getBody(); // 调用SDK生成表单
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        httpResponse.setContentType("text/html;charset=" + CHARSET);
        httpResponse.getWriter().write(form);// 直接将完整的表单html输出到页面
        httpResponse.getWriter().flush();
        httpResponse.getWriter().close();
        emo();
    }

    public static void emo() throws InterruptedException{
//        Map<String,String> imageMap = new HashMap<>();
//        imageMap.put("image","zfb.png");
        Thread.sleep(1000);
        String emo = MailUtil.send("1320153843@qq.com","MCAKE蛋糕",
                 "<h1>您好！</h1>"
                + "<h2>宁选择的蛋糕已经支付成功！大约在2~4小时后发货</h1>"
                + new Date(),true, FileUtil.file("D:\\vsCode案例\\cake2\\img\\logo.png"));
//        System.out.println(emo);
//        for (int i = 0; i<1; i++){
//            System.out.println(emo);
//        }
    }

//    @RequestMapping(value = "/returnUrl", method = RequestMethod.GET)
//    public String returnUrl(HttpServletRequest request, HttpServletResponse response)
//            throws IOException, AlipayApiException {
//        System.out.println("=================================同步回调=====================================");
//        // 获取支付宝GET过来反馈信息
//        Map<String, String> params = new HashMap<String, String>();
//        Map<String, String[]> requestParams = request.getParameterMap();
//        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext(); ) {
//            String name = (String) iter.next();
//            String[] values = (String[]) requestParams.get(name);
//            String valueStr = "";
//            for (int i = 0; i < values.length; i++) {
//                valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";
//            }
//            // 乱码解决，这段代码在出现乱码时使用
//            valueStr = new String(valueStr.getBytes("utf-8"), "utf-8");
//            params.put(name, valueStr);
//        }
//
//        System.out.println(params);//查看参数都有哪些
//        boolean signVerified = AlipaySignature.rsaCheckV1(params, ALIPAY_PUBLIC_KEY, CHARSET, SIGN_TYPE); // 调用SDK验证签名
//        //验证签名通过
//        if (signVerified) {
//            // 商户订单号
//            String out_trade_no = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"), "UTF-8");
//
//            // 支付宝交易号
//            String trade_no = new String(request.getParameter("trade_no").getBytes("ISO-8859-1"), "UTF-8");
//
//            // 付款金额
//            String total_amount = new String(request.getParameter("total_amount").getBytes("ISO-8859-1"), "UTF-8");
//
//
//            System.out.println("商户订单号=" + out_trade_no);
//            System.out.println("支付宝交易号=" + trade_no);
//            System.out.println("付款金额=" + total_amount);
//
//
//            //支付成功，修复支付状态
////             payService.updateById(Integer.valueOf(out_trade_no));
//            return "text.html";//跳转付款成功页面
//        } else {
//            return "no";//跳转付款失败页面
//        }
//    }
}
